//
//  InAppPurchase.m
//  Brand
//
//  Created by Lin Eidan on 14-5-20.
//  Copyright (c) 2014年 Faker. All rights reserved.
//

#import "InAppPurchase.h"
#import "Header.h"
#import "config.h"


#define BuyProductionID1                @"com.produce.kkd1"  //30
#define BuyProductionID2                @"com.produce.kkd2"  //90
#define BuyProductionID3                @"com.produce.kkd3"  //180
#define BuyURL                          @"http://kuiba.haomee.net/?m=IosPay&a=createVipOrder"
#define CheckURL                        @"http://kuiba.haomee.net/?m=IosPay&a=checkVipOrderState"

@interface InAppPurchase ()

@property (strong, nonatomic) NSString *buyProId;
@property (strong, nonatomic) NSString *sid;

@end

@implementation InAppPurchase

+ (InAppPurchase *)sharedInstance{
    static InAppPurchase *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[InAppPurchase alloc] init];
    });
    return _sharedInstance;
}

-(id)init{
    self =[super init];
    if (self) {
        [self initBuy];
    }
    return self;
}

#pragma -mark 应用内购买
-(void)initBuy{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

-(void)getVIP:(NSString *)type{
    NSLog(@"ee   %@",ISSandBox);
    if ([SKPaymentQueue canMakePayments] && ![Common isJailBroken] && ![Common isJailBreak]) {
        [self requestProductData:type];
    }
    else{
        NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError title:NotifyTitleWarning message:@"用户禁止应用内付费购买" delegate:nil];
        [alert show];
    }
    
}

-(void)requestProductData:(NSString *)type
{
    int num = [type intValue];
    if (num == 1) {
        self.buyProId = BuyProductionID1;
    }else if(num == 2){
        self.buyProId = BuyProductionID2;
    }else{
        self.buyProId = BuyProductionID3;
    }
    
    //my
    NSString *url = BuyURL;
    
    if (![[UserObj sharedInstance] isLegalLogin]) {
        [PopTips tipsAtTop:kApp.rootNav.view Msg:NotifyLoginFirst];
        return;
    }
    
    [kApp displayWaitViewWithAllMaskView:NO];
    [[DownloadGetData sharedInstance] startPost:url andInfo:@{@"uid" : [[UserObj sharedInstance] uid], @"ak" : [[UserObj sharedInstance] accessKey], @"itemId" : type } andDataBodyBlock:^(id<AFMultipartFormData> formData) {
        
    } andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if (isSuccess) {
            NSDictionary *dic = responseObj;
            if ([dic objectForKey:@"flag"]) {
                self.sid = [dic objectForKey:@"sid"];
                
                //apple
                NSSet *nsset = [NSSet setWithObject:self.buyProId];
                SKProductsRequest *request=[[SKProductsRequest alloc] initWithProductIdentifiers: nsset];
                request.delegate=self;
                [request start];
                
            }else{
                [kApp hideWaitView];
                NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError title:NotifyTitleWarning message:NotifyIAPFailed delegate:nil];
                [alert show];
            }
            
        }else{
            [kApp hideWaitView];
            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:nil];
        }

    }];
    
}

#pragma -mark requestDelegate 请求商品

//request success
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSArray *myProduct = response.products;
    if (myProduct.count == 0) {
        [kApp hideWaitView];
        NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError title:NotifyTitleWarning message:NotifyIAPFailed delegate:nil];
        [alert show];
        return;
    }
    
    for(SKProduct *product in myProduct){
        NSLog(@"product info");
        NSLog(@"产品标题 %@" , product.localizedTitle);
        NSLog(@"产品描述信息: %@" , product.localizedDescription);
        NSLog(@"价格: %@" , product.price);
        NSLog(@"Product id: %@" , product.productIdentifier);
    }
    
    //开始购买
    SKPayment * payment = [SKPayment paymentWithProduct:myProduct[0]];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
//request failed
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"-------弹出请求的错误信息----------");
    [kApp hideWaitView];
    NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError title:NotifyTitleWarning message:NotifyIAPFailed delegate:nil];
    [alert show];
}
//request finish
-(void)requestDidFinish:(SKRequest *)request{
    NSLog(@"----------请求信息结束--------------");
}

#pragma -mark  SKPaymentTransactionObserver 购买商品

//交易结果,会调用多次
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    NSLog(@"-----paymentQueue--------");
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased://交易完成
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:  //交易失败
                [self failedTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored: //已经购买过该商品
                [self restoreTransaction:transaction];
                break;
            case SKPaymentTransactionStatePurchasing:  ////商品添加进列表
                NSLog(@"-----商品添加进列表 --------");
                break;
            default:
                break;
        }
    }
}

//apple购买成功
- (void)completeTransaction: (SKPaymentTransaction *)transaction{
    
    NSString *product = transaction.payment.productIdentifier;
    if ([product length] > 0) {
        
        NSString *url = CheckURL;
        
        NSString *receipt = [transaction.transactionReceipt base64Encoding];
        if (![[UserObj sharedInstance] isLegalLogin] || !self.sid || !receipt) {
            [kApp hideWaitView];
            [PopTips tipsAtTop:kApp.rootNav.view Msg:NotifyIAPFailed];
            return;
        }
        
        [[DownloadGetData sharedInstance] startPost:url andInfo:@{@"uid" : [[UserObj sharedInstance] uid], @"ak" : [[UserObj sharedInstance] accessKey], @"receipt" : receipt ,@"sandbox" :ISSandBox, @"sid" : self.sid } andDataBodyBlock:^(id<AFMultipartFormData> formData) {
            
        }andRequestCompletion:^(id responseObj, BOOL isSuccess) {
            [kApp hideWaitView];
            if (isSuccess) {
                NSDictionary *dic = responseObj;
                if ([dic objectForKey:@"flag"]) {
                    if ([self.delegate respondsToSelector:@selector(InAppPurchaseSccessOrNot:)]) {
                        [self.delegate InAppPurchaseSccessOrNot:YES];
                    }
                    NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleSuccess title:NotifyNormal message:NotifyIAPSuccess delegate:nil];
                    [alert show];
                }else{
                    NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError title:NotifyTitleWarning message:NotifyIAPFailed delegate:nil];
                    [alert show];
                }
                
            }else{
                [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:nil];
            }
        }];
    }
    // Remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
}

//购买失败
- (void)failedTransaction: (SKPaymentTransaction *)transaction{
    [kApp hideWaitView];
    if (transaction.error.code != SKErrorPaymentCancelled){  //不是用户自己取消，而导致的失败，需要提示。
        NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError title:NotifyTitleWarning message:NotifyIAPFailed delegate:nil];
        [alert show];
    }
    
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

//已经购买过该商品
- (void)restoreTransaction: (SKPaymentTransaction *)transaction{
    [kApp hideWaitView];
    NSLog(@"交易恢复处理");
    
}

//已经购买过该商品恢复成功
-(void)paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction{
    
}

//已经购买过该商品恢复失败
-(void)paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error{
    NSLog(@"-------restore failed----");
}
@end
